package com.jarvis.hospital.patient;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jarvis.hospital.MainActivity;
import com.jarvis.hospital.R;
import com.jarvis.hospital.SettingActivity;
import com.jarvis.hospital.common.BaseFragment;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.contants.ContactModel;
import com.jarvis.hospital.contants.ContactsAdapter;
import com.jarvis.hospital.contants.LetterComparator;
import com.jarvis.hospital.contants.PinnedHeaderDecoration;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.model.PatientListModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;
import com.nanchen.wavesidebar.FirstLetterUtil;
import com.nanchen.wavesidebar.SearchEditText;
import com.nanchen.wavesidebar.Trans2PinYinUtil;
import com.nanchen.wavesidebar.WaveSideBarView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by jarvis.liu on 2016-11-02.
 */

public class PatientManageFragment extends BaseFragment {
    private List<ContactModel> mContactModels;
    private List<ContactModel> mShowModels;
    private ContactsAdapter mAdapter;

    @BindView(R.id.main_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.main_side_bar)
    WaveSideBarView mWaveSideBarView;
    @BindView(R.id.main_search)
    EditText mSearchEditText;
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_right)
    RelativeLayout rel_right;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_right)
    TextView tv_right;
    private ApiService service;
    private String type;
    public static PatientManageFragment newInstance(String type) {
        Bundle args = new Bundle();
        PatientManageFragment fragment = new PatientManageFragment();
        fragment.setArguments(args);
        fragment.type=type;
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_patient_manage;
    }

    @Override
    public void initData() {
        showDialog("加载中");
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.getPatientListByDoctor(userId, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<PatientListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<PatientListModel> patientListModelResponseData) {
                        if (patientListModelResponseData != null) {
                            int resultCode = patientListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                List<ContactModel> patientList = patientListModelResponseData.getData().getPatientList();
                                for (int i = 0; i < patientList.size(); i++) {
                                    ContactModel contactModel = patientList.get(i);
                                    contactModel.setIndex( FirstLetterUtil.getFirstLetter(contactModel.getPatientName()));

                                }
                                mContactModels = new ArrayList<>();
                                mContactModels.addAll(patientList);
                                Collections.sort(mContactModels, new LetterComparator());
                                mShowModels.clear();
                                mShowModels.addAll(mContactModels);
                                mAdapter.notifyDataSetChanged();
                            } else {
                                showTextToast(patientListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setStatus(true);
            initData();
        }

    }
    @Override
    protected void initView() {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userRole = userModel.getUserRole();
        if("patient".equals(userRole)){
            rel_left.setVisibility(View.GONE);
            tv_right.setText("设置");
            rel_right.setVisibility(View.VISIBLE);
            rel_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(SettingActivity.class);
                }
            });
        }
        service = RequestApi.create(ApiService.class);
        setStatus(true);
        tv_title.setText("病人管理");
        rel_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        mShowModels = new ArrayList<>();
        mAdapter = new ContactsAdapter(mShowModels, new ContactsAdapter.OnRecyclerviewItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {
                if("0".equals(type)){
                    Intent i=new Intent();
                    i.putExtra("account", mShowModels.get(position));
                    getActivity().setResult(4,i);
                    getActivity().finish();
                }else {
                    Bundle bundle = new Bundle();
                    bundle.putString("name", mShowModels.get(position).getPatientName());
                    bundle.putString("smsReceiverId", mShowModels.get(position).getPatientId());
                    startActivity(MessageDetailsActivity.class,bundle);
                }
            }
        });

        // RecyclerView设置相关
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        final PinnedHeaderDecoration decoration = new PinnedHeaderDecoration();
        decoration.registerTypePinnedHeader(1, new PinnedHeaderDecoration.PinnedHeaderCreator() {
            @Override
            public boolean create(RecyclerView parent, int adapterPosition) {
                return true;
            }
        });
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setAdapter(mAdapter);

        // 侧边设置相关
        mWaveSideBarView.setOnSelectIndexItemListener(new WaveSideBarView.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String letter) {
                for (int i=0; i<mContactModels.size(); i++) {
                    if (mContactModels.get(i).getIndex().equals(letter)) {
                        ((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });


        // 搜索按钮相关
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mShowModels.clear();
                for (ContactModel model : mContactModels) {
                    String str = Trans2PinYinUtil.trans2PinYin(model.getPatientName());
                    if (str.contains(s.toString()) || model.getPatientName().contains(s.toString())) {
                        mShowModels.add(model);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mContactModels != null){
            mContactModels.clear();
            mContactModels = null;
        }
    }
}
